<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>图书列表</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.27.2/axios.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/art-template/4.13.2/lib/template-web.js"></script>
</head>

<body>
    <h2>图书列表</h2>

    <button onclick="window.location='/cient/add.html'">添加</button>
    <ul>
    </ul>

    <script id="lis" type="text/html">
    <%
      books.forEach(b => {
    %>
      <li>
        <%=b._id%>--<%=b.name%>--<%=b.author%>--<%=b.price%>
        <button onclick="window.location='update.html?id=<%=b._id%>'">修改</button>
        <button onclick="delBook('<%=b._id%>')">删除</button>
      </li>
    <%
      })
    %>
  </script>

    <script>
        // 请求获取图书列表并渲染成列表
        // async function getBooks() {
        //   const response = await axios('http://localhost:9999/book')
        //   const books = response.data.data
        //   // console.log(books)
        //   // 渲染模板, 生成标签字符串
        //   const html = template('lis', {books: books})
        //   // 插入到ul中
        //   document.querySelector('ul').innerHTML = html
        // }
        // getBooks()
        axios('http://localhost:9999/book').then(
            (response) => {
                const books = response.data.data
                const html = template('lis', {books: books})
                document.querySelector('ul').innerHTML = html
            }
        ).catch((error) => {
            console.log(error)
        })


        // 发起删除请求，并带上body参数
        async function delBook(id) {
            // await axios({
            //     url: 'http://localhost:9999/book',
            //     method: 'delete',
            //     params: {
            //         id
            //     }
            // })
            await axios.delete('http://localhost:9999/book', { params: {id} })
            window.location = '/cient/books.html'
        }
    </script>
</body>

</html>